package com.sx.micowell.module.sport

import android.graphics.Color
import android.util.TypedValue
import android.view.View
import android.view.ViewGroup
import android.widget.ImageView
import android.widget.LinearLayout
import android.widget.ProgressBar
import android.widget.TextView
import androidx.constraintlayout.widget.ConstraintLayout
import androidx.core.content.ContextCompat
import com.alibaba.android.arouter.facade.annotation.Autowired
import com.alibaba.android.arouter.facade.annotation.Route
import com.dou361.ijkplayer.widget.IRenderView
import com.dou361.ijkplayer.widget.PlayStateParams
import com.dou361.ijkplayer.widget.PlayStateParams.STATE_PAUSED
import com.dou361.ijkplayer.widget.PlayStateParams.STATE_PLAYING
import com.dou361.ijkplayer.widget.PlayerView
import com.example.mvvm.bar.SelectorDrawable
import com.example.mvvm.bar.TitleBar
import com.example.mvvm.base.data.DataBindingConfig
import com.example.mvvm.until.LogUtils
import com.example.mvvm.until.SPUtils
import com.github.mikephil.charting.charts.LineChart
import com.github.mikephil.charting.components.YAxis
import com.github.mikephil.charting.data.Entry
import com.github.mikephil.charting.data.LineData
import com.github.mikephil.charting.data.LineDataSet
import com.github.mikephil.charting.formatter.IndexAxisValueFormatter
import com.google.gson.Gson
import com.gyf.immersionbar.ImmersionBar
import com.sx.micowell.BR
import com.sx.micowell.R
import com.sx.micowell.databinding.ActStartSportBinding
import com.sx.micowell.framework.app.MyApplication
import com.sx.micowell.framework.arouth.RoutePath
import com.sx.micowell.framework.model.Sport2Model
import com.sx.micowell.framework.serialPort.SerialPortActivity
import com.sx.micowell.framework.tools.cmd.CmdException
import com.sx.micowell.framework.view.chartManager.initUi
import com.sx.micowell.framework.view.chartManager.scaleX_OBJ
import com.sx.micowell.framework.view.chartManager.setNetData
import com.sx.micowell.framework.view.dialog.DialogError
import com.sx.micowell.framework.view.dialog.DialogPowerSetting
import com.sx.micowell.module.sport.engine.SportEngineImpl
import com.sx.widget.app.DisplayUtil
import tv.danmaku.ijk.media.player.IMediaPlayer
import java.math.RoundingMode
import java.util.*
import kotlin.collections.HashMap

/**
 * @Description
 * @Author 梁浩文
 * @Date 2021/12/2 9:10
 */
@Route(path = RoutePath.SPORT_START)
class Sport2Activity : SerialPortActivity<ActStartSportBinding>() {
    override fun getDataBindingConfig(): DataBindingConfig =
        DataBindingConfig(R.layout.act_start_sport, BR.viewModel, viewModel)

    @Autowired(name = "mode")
    @JvmField
    var mode: Int = 1057

    private lateinit var player: PlayerView

    val powerDialog: DialogPowerSetting.Builder by lazy {
        DialogPowerSetting.Builder(this, viewModel)
    }

    val errorDialog: DialogError.Builder by lazy {
        DialogError.Builder(this)
    }

    var sportEngine: SportEngineImpl? = null

    private val viewModel: Sport2Model by lazy {
        getActivityScopeViewModel(Sport2Model::class.java)
    }


    override fun initView() {

        binding.appVideoBox.addView(ImageView(this).also {
            it.id = R.id.id_add_m
            var param = ConstraintLayout.LayoutParams(
                resources.getDimension(R.dimen.dp_60).toInt(),
                resources.getDimension(R.dimen.dp_60).toInt()
            )
            param.topToTop = ConstraintLayout.LayoutParams.PARENT_ID
            param.bottomToBottom = ConstraintLayout.LayoutParams.PARENT_ID
            param.bottomMargin = resources.getDimension(R.dimen.dp_200).toInt()
            param.leftToLeft = ConstraintLayout.LayoutParams.PARENT_ID
            param.rightToRight = ConstraintLayout.LayoutParams.PARENT_ID
            var selectorDrawable = SelectorDrawable.Builder()
            selectorDrawable.setSelected(ContextCompat.getDrawable(this, R.drawable.ic_icon_play))
            selectorDrawable.setDefault(ContextCompat.getDrawable(this, R.drawable.ic_icon_plus))
            it.setImageDrawable(selectorDrawable.build())
            it.layoutParams = param
            it.setOnClickListener(this)
        })
        binding.appVideoBox.addView(TitleBar(this).also {
            it.id = R.id.id_add_t
            it.setRightTitleColor(Color.WHITE)
            it.setLineVisible(false)
            it.setRightTitle("设置")
            it.setTitleColor(Color.WHITE)
            it.getmTitleView().paint.isFakeBoldText = true
            it.setLeftIcon(R.drawable.bar_arrows_left_white)
            var layoutParams = ConstraintLayout.LayoutParams(
                ConstraintLayout.LayoutParams.MATCH_PARENT,
                ConstraintLayout.LayoutParams.WRAP_CONTENT
            )
            layoutParams.topToTop = ConstraintLayout.LayoutParams.PARENT_ID
            it.layoutParams = layoutParams
            ImmersionBar.with(this).titleBar(it).init()
            it.setBackgroundColor(Color.TRANSPARENT)
            it.setOnTitleBarListener(this)
        })
        binding.appVideoBox.addView(View.inflate(this, R.layout.view_progress, null).also {
            var layoutParams = ConstraintLayout.LayoutParams(
                ConstraintLayout.LayoutParams.MATCH_PARENT,
                ConstraintLayout.LayoutParams.WRAP_CONTENT
            )
            layoutParams.topToBottom = R.id.id_add_t
            it.layoutParams = layoutParams
        })
        binding.appVideoBox.addView(ImageView(this).also {
            it.id = R.id.id_add_ban
            var layoutParams = ConstraintLayout.LayoutParams(
                resources.getDimension(R.dimen.dp_30).toInt(),
                resources.getDimension(R.dimen.dp_30).toInt()
            )
            layoutParams.topToBottom = R.id.id_add_t
            layoutParams.topMargin = resources.getDimension(R.dimen.dp_16).toInt()
            layoutParams.rightToRight = ConstraintLayout.LayoutParams.PARENT_ID
            layoutParams.rightMargin = resources.getDimension(R.dimen.dp_16).toInt()
            var selectorDrawable = SelectorDrawable.Builder()
            selectorDrawable.setSelected(
                ContextCompat.getDrawable(
                    this,
                    R.drawable.ic_icon_police_2
                )
            )
            selectorDrawable.setDefault(
                ContextCompat.getDrawable(
                    this,
                    R.drawable.ic_icon_police_1
                )
            )
            it.layoutParams = layoutParams
            it.setImageDrawable(selectorDrawable.build())
            it.setOnClickListener(this)
        })
        binding.appVideoBox.addView(ImageView(this).also {
            it.id = R.id.id_add_music
            var layoutParams = ConstraintLayout.LayoutParams(
                resources.getDimension(R.dimen.dp_30).toInt(),
                resources.getDimension(R.dimen.dp_30).toInt()
            )
            layoutParams.topToBottom = R.id.id_add_ban
            layoutParams.topMargin = resources.getDimension(R.dimen.dp_16).toInt()
            layoutParams.rightToRight = ConstraintLayout.LayoutParams.PARENT_ID
            layoutParams.rightMargin = resources.getDimension(R.dimen.dp_16).toInt()
            var selectorDrawable = SelectorDrawable.Builder()
            selectorDrawable.setSelected(
                ContextCompat.getDrawable(
                    this,
                    R.drawable.ic_icon_music_off
                )
            )
            selectorDrawable.setDefault(
                ContextCompat.getDrawable(
                    this,
                    R.drawable.ic_icon_music_on
                )
            )
            it.layoutParams = layoutParams
            it.setImageDrawable(selectorDrawable.build())
            it.setOnClickListener(this)
        })
        binding.appVideoBox.addView(ImageView(this).also {
            it.id = R.id.id_add_body
            var layoutParams = ConstraintLayout.LayoutParams(
                resources.getDimension(R.dimen.dp_64).toInt(),
                resources.getDimension(R.dimen.dp_80).toInt()
            )
            layoutParams.topToTop = ConstraintLayout.LayoutParams.PARENT_ID
            layoutParams.bottomToBottom = ConstraintLayout.LayoutParams.PARENT_ID
            layoutParams.rightToRight = ConstraintLayout.LayoutParams.PARENT_ID
            layoutParams.rightMargin = resources.getDimension(R.dimen.dp_5).toInt()
            it.setImageResource(R.drawable.ic_outline)
            it.layoutParams = layoutParams
        })
        binding.appVideoBox.addView(CompletedView(this).also {
            it.id = R.id.id_add_p
            it.setProgress(0, "X0")
            var layoutParams = ConstraintLayout.LayoutParams(
                resources.getDimension(R.dimen.dp_64).toInt(),
                resources.getDimension(R.dimen.dp_64).toInt()
            )
            layoutParams.topToBottom = R.id.id_add_m
            layoutParams.leftToLeft = ConstraintLayout.LayoutParams.PARENT_ID
            layoutParams.leftMargin = resources.getDimension(R.dimen.dp_29).toInt()
            it.layoutParams = layoutParams
        })
        binding.appVideoBox.addView(ImageView(this).also {
            it.id = R.id.id_add_m1
            var layoutParams = ConstraintLayout.LayoutParams(
                ViewGroup.LayoutParams.WRAP_CONTENT,
                ViewGroup.LayoutParams.WRAP_CONTENT
            )
            layoutParams.leftToLeft = ConstraintLayout.LayoutParams.PARENT_ID
            layoutParams.leftMargin = resources.getDimension(R.dimen.dp_20).toInt()
            layoutParams.topToBottom = R.id.id_add_p
            layoutParams.topMargin = resources.getDimension(R.dimen.dp_12).toInt()
            it.setPadding(
                resources.getDimension(R.dimen.dp_5).toInt(),
                resources.getDimension(R.dimen.dp_5).toInt(),
                resources.getDimension(R.dimen.dp_5).toInt(),
                resources.getDimension(R.dimen.dp_5).toInt()
            )
            it.layoutParams = layoutParams
            it.setImageResource(R.drawable.ic_icon_left)
            it.setOnClickListener(this)
        })
        binding.appVideoBox.addView(TextView(this).also {
            it.id = R.id.id_add_t1
            var layoutParams = ConstraintLayout.LayoutParams(
                ViewGroup.LayoutParams.WRAP_CONTENT,
                ViewGroup.LayoutParams.WRAP_CONTENT
            )
            layoutParams.leftToRight = R.id.id_add_m1
            layoutParams.topToTop = R.id.id_add_m1
            layoutParams.bottomToBottom = R.id.id_add_m1
            it.layoutParams = layoutParams
            it.setOnClickListener(this)
            it.setTextColor(Color.WHITE)
            it.setTextSize(TypedValue.COMPLEX_UNIT_PX, resources.getDimension(R.dimen.sp_24))
            it.paint.isFakeBoldText = true
            it.setText("1")
        })
        binding.appVideoBox.addView(TextView(this).also {
            it.id = R.id.id_add_t2
            var layoutParams = ConstraintLayout.LayoutParams(
                ViewGroup.LayoutParams.WRAP_CONTENT,
                ViewGroup.LayoutParams.WRAP_CONTENT
            )
            layoutParams.leftToRight = R.id.id_add_t1
            layoutParams.topToTop = R.id.id_add_m1
            layoutParams.bottomToBottom = R.id.id_add_t1
            layoutParams.leftMargin = resources.getDimension(R.dimen.dp_5).toInt()
            it.layoutParams = layoutParams
            it.includeFontPadding = false
            it.setText("/")
            it.setTextSize(TypedValue.COMPLEX_UNIT_PX, resources.getDimension(R.dimen.sp_13))
            it.setTextColor(ContextCompat.getColor(this, R.color.white65))
        })
        binding.appVideoBox.addView(TextView(this).also {
            it.id = R.id.id_add_t3
            var layoutParams = ConstraintLayout.LayoutParams(
                ViewGroup.LayoutParams.WRAP_CONTENT,
                ViewGroup.LayoutParams.WRAP_CONTENT
            )
            layoutParams.leftToRight = R.id.id_add_t2
            layoutParams.topToTop = R.id.id_add_m1
            layoutParams.bottomToBottom = R.id.id_add_t1
            it.layoutParams = layoutParams
            it.includeFontPadding = false
            it.setText("3")
            it.setTextSize(TypedValue.COMPLEX_UNIT_PX, resources.getDimension(R.dimen.sp_13))
            it.setTextColor(ContextCompat.getColor(this, R.color.white65))
        })
        binding.appVideoBox.addView(ImageView(this).also {
            it.id = R.id.id_add_m2
            var layoutParams = ConstraintLayout.LayoutParams(
                ViewGroup.LayoutParams.WRAP_CONTENT,
                ViewGroup.LayoutParams.WRAP_CONTENT
            )
            layoutParams.leftToRight = R.id.id_add_t3
            layoutParams.topToTop = R.id.id_add_m1
            it.layoutParams = layoutParams
            it.setPadding(
                resources.getDimension(R.dimen.dp_5).toInt(),
                resources.getDimension(R.dimen.dp_5).toInt(),
                resources.getDimension(R.dimen.dp_5).toInt(),
                resources.getDimension(R.dimen.dp_5).toInt()
            )
            it.setImageResource(R.drawable.ic_icon_right)
            it.setOnClickListener(this)
        })
        binding.appVideoBox.addView(View.inflate(this, R.layout.view_sport, null).also {
            it.id = R.id.id_add_value
            var layoutParams = ConstraintLayout.LayoutParams(
                ViewGroup.LayoutParams.MATCH_PARENT,
                ViewGroup.LayoutParams.WRAP_CONTENT
            )
            layoutParams.topToBottom = R.id.id_add_body
            layoutParams.topMargin = resources.getDimension(R.dimen.dp_35).toInt()
            it.layoutParams = layoutParams
        })
        binding.appVideoBox.addView(LineChart(this).also {
            it.id = R.id.id_add_char
            var layoutParams = ConstraintLayout.LayoutParams(
                ViewGroup.LayoutParams.MATCH_PARENT,
                0
            )
            layoutParams.topToBottom = R.id.id_add_value
            layoutParams.bottomToBottom = ConstraintLayout.LayoutParams.PARENT_ID
            it.layoutParams = layoutParams
            var netDataSet = it.setNetData(null, viewModel.lineListData)
            it.initUi()
            it.offsetTopAndBottom(30)
            it.axisLeft.isEnabled = false
            it.axisRight.isEnabled = true
            it.axisRight.setDrawZeroLine(false)
            it.axisRight.textColor = Color.WHITE//Y轴 文字颜色
            it.axisRight.textSize = DisplayUtil.px2dip(
                MyApplication.instance(),
                MyApplication.instance().resources.getDimension(R.dimen.sp_12)
            ).toFloat();//Y轴 文字大小
            it.axisRight.axisMinimum = 0f
            it.axisRight.gridColor = ContextCompat.getColor(this, R.color.white45)
            it.axisRight.setDrawGridLines(true)
            it.xAxis.textColor = Color.WHITE
            it.xAxis.setDrawLabels(true)
            it.xAxis.valueFormatter = IndexAxisValueFormatter()
            when (mode) {
                1053, 1048 -> {
                    //观察者模式
                    //恒等张力
                    netDataSet.fillColor = Color.parseColor("#00DA8B")
                    netDataSet.fillAlpha = 25
                }
                1017, 1037, 1036, 1035, 1057, 1034 -> {
                    //极限 划船 高尔夫 链条
                    netDataSet.setDrawFilled(false)
                    netDataSet.setMode(LineDataSet.Mode.LINEAR)
                }
//                1057, 1034 -> {
//                    //力量递增 递减
//                    netDataSet.setDrawFilled(true)
//                    netDataSet.setLineWidth(0f)
//                    netDataSet.fillColor = ContextCompat.getColor(this, R.color.them)
//                    netDataSet.setMode(LineDataSet.Mode.STEPPED)
//                }
            }
            it.data = LineData(netDataSet)
        })

        player = PlayerView(this)
            .setScaleType(IRenderView.AR_MATCH_PARENT)
            .setShowSpeed(false)
            .forbidTouch(false)
            .hideHideTopBar(true)
            .hideSteam(true)
            .hideFullscreen(true)
            .hideRotation(true)
            .hideBottonBar(true)
            .hideCenterPlayer(true)
            .hideAllUI()
        findViewById<LinearLayout>(R.id.ll_bg).setBackgroundColor(Color.parseColor("#693476"))
        player.setOnInfoListener(object : IMediaPlayer.OnInfoListener {
            override fun onInfo(p0: IMediaPlayer?, p1: Int, p2: Int): Boolean {
                LogUtils.i("setOnInfoListener p1${p1}  p2${p2}")
                if (p1 == PlayStateParams.STATE_COMPLETED) {
                    //结束
                    player.startPlay()
                } else if (p1 == STATE_PAUSED) {
                    viewModel.pauseSport = true
                } else if (p1 == STATE_PLAYING) {
                    viewModel.pauseSport = false
                }
                return true
            }
        })
        player.setProgressListener {
            LogUtils.i("setProgressListener${it}")
            var progressBar = findViewById<ProgressBar>(R.id.progress_view)
            progressBar.progress=it
        }

    }

    fun startPlay(url: String) {
        player.stopPlay()
        player.setPlaySource(
            MyApplication.instance().getProxy(this)
                ?.getProxyUrl(url)
        ).startPlay()
    }

    override fun initData() {
        viewModel.powerLiveData.value = SPUtils.getInstance().getInt("power", 10)
        var body = "{\n" +
                "    \"id\": 1,\n" +
                "    \"curriculumTitle\": \"第一个课程\",\n" +
                "    \"curriculumContent\": \"以后想要一口气做100个俯卧撑\",\n" +
                "    \"curriculumCover\": \"/micowell/adminuser/20211117/163713518709616647.jpg\",\n" +
                "    \"duration\": \"10\",\n" +
                "    \"calorie\": \"1000\",\n" +
                "    \"physicalPosition\": \"chest\",\n" +
                "    \"isVip\": \"Y\",\n" +
                "    \"studyNum\": 0,\n" +
                "    \"studyStatus\": null,\n" +
                "    \"movementModelList\": [\n" +
                "      {\n" +
                "        \"id\": 5,\n" +
                "        \"movementId\": 25,\n" +
                "        \"movementTitle\": \"站姿手柄二头弯举\",\n" +
                "       \"categoryName\": \"极限挑战模式\",\n" +
                "       \"categoryCmd\": 5,\n" +
                "       \"fzCategoryCmd\": 1,\n" +
                "       \"fzCategoryId\": 0,\n" +
                "        \"cover\": \"/micowell/adminuser/20211119/163731111909773984.png\",\n" +
                "        \"setCount\": 3,\n" +
                "        \"actionCount\": \"5\",\n" +
                "        \"sleepTime\": 0,\n" +
                "        \"studyStatus\": \"0\",\n" +
                "        \"categoryId\": 1017,\n" +
                "        \"fzCategoryId\": 1054,\n" +
                "        \"movementCover\": \"/micowell/adminuser/20211119/163729038260754898.jpg\",\n" +
                "        \"url\": \"https://yaoni2020-1301520140.cos.ap-guangzhou.myqcloud.com/yn/163878162611693328.mp4\",\n" +
                "        \"introduce\": \"将产品把手调至下方。双手握住杠铃，挺直身体，手掌朝上，大臂夹紧身体，肘关节一只垂直地面。二头肌发力，让你的小臂去找肩膀。下方时伸展肘部，手下放到腿部前侧。\",\n" +
                "        \"duration\": 0,\n" +
                "        \"benefit\": \"这是一项经典的二头肌运动。它塑造了强壮的二头肌，有助于练背动作力量的增长。\",\n" +
                "        \"physicalPosition\": \"arm\",\n" +
                "        \"svg\": null,\n" +
                "        \"positionCover\": \"/micowell/adminuser/20211119/163729040050300373.png\"\n" +
                "      },\n" +
                "      {\n" +
                "        \"id\": 6,\n" +
                "        \"movementId\": 14,\n" +
                "        \"movementTitle\": \"杠铃二头弯举\",\n" +
                "       \"categoryName\": \"极限挑战模式\",\n" +
                "       \"categoryCmd\": 5,\n" +
                "       \"fzCategoryCmd\": 1,\n" +
                "       \"fzCategoryId\": 1,\n" +
                "        \"cover\": \"/micowell/adminuser/20211119/163731118102770259.jpg\",\n" +
                "        \"setCount\": 3,\n" +
                "        \"actionCount\": \"5\",\n" +
                "        \"sleepTime\": 30,\n" +
                "        \"studyStatus\": \"0\",\n" +
                "        \"categoryId\": 1036,\n" +
                "        \"fzCategoryId\": 1053,\n" +
                "        \"movementCover\": \"/micowell/adminuser/20211119/163728821297636268.jpg\",\n" +
                "        \"url\": \"http://vfx.mtime.cn/Video/2019/03/19/mp4/190319212559089721.mp4\",\n" +
                "        \"introduce\": \"将产品把手调至下方。双手握住杠铃，挺直身体，手掌朝上，大臂夹紧身体，肘关节一只垂直地面。二头肌发力，让你的小臂去找肩膀。下方时伸展肘部，手下放到腿部前侧。\",\n" +
                "        \"duration\": 0,\n" +
                "        \"benefit\": \"这是一项经典的二头肌运动。它塑造了强壮的二头肌，有助于杠铃弯腰划船这样的练背动作。\",\n" +
                "        \"physicalPosition\": \"arm\",\n" +
                "        \"svg\": null,\n" +
                "        \"positionCover\": \"/micowell/adminuser/20211119/163728822594770661.png\"\n" +
                "      }\n" +
                "    ],\n" +
                "    \"clevel\": \"1\"\n" +
                "  }"
        var sportBean = Gson().fromJson<SportBean>(body, SportBean::class.java)
        viewModel.mode = mode
        viewModel.sportList.addAll(sportBean.movementModelList)
        viewModel.startCache(this)
        sportEngine = SportEngineImpl(viewModel)
    }

    override fun initViewObservable() {
        super.initViewObservable()
        viewModel.powerLiveData.observe(this) {
            //修改力量
            var movementModel = viewModel.sportList[viewModel.currentPosition.value as Int]
            var power = viewModel.getPower()
            send(
                10,
                viewModel.getMode(movementModel.categoryCmd, movementModel.fzCategoryCmd),
                power[0],
                power[1]
            )
            SPUtils.getInstance().put("power", it)
        }
        viewModel.currentPosition.observe(this) {
            var get = viewModel.sportList.get(it)
            startPlay(get.url)
            var movementModel = viewModel.sportList[it]
            var power = viewModel.getPower()
            send(
                10,
                viewModel.getMode(movementModel.categoryCmd, movementModel.fzCategoryCmd),
                power[0],
                power[1]
            )
            var titleBar = findViewById<TitleBar>(R.id.id_add_t)
            titleBar.setTitle(movementModel.movementTitle)
        }
        viewModel.sportDataUi.observe(this) {
            //进度条
            findViewById<CompletedView>(R.id.id_add_p).setProgress(
                it.currentCount.toBigDecimal()
                    .divide(it.currentActionCountGross.toBigDecimal(), 2, RoundingMode.CEILING)
                    .multiply(100.toBigDecimal()).toInt(), "X${it.currentCount}"
            )
            //当前动作索引
            findViewById<TextView>(R.id.id_add_t1).text = (it.actionIndex + 1).toString()
            //动作总数
            findViewById<TextView>(R.id.id_add_t3).text = it.allAction.toString()
            //卡路里
            findViewById<TextView>(R.id.tv_cal).text = it.kcal.toString()
            //已完成次数
            findViewById<TextView>(R.id.tv_finish_count).text = it.currentCount.toString()
            //次数总量
            findViewById<TextView>(R.id.tv_all_count).text = it.currentActionCountGross.toString()
            //已完成组数
            findViewById<TextView>(R.id.tv_finish_group).text = it.currentGroup.toString()
            //组数总量
            findViewById<TextView>(R.id.tv_all_group).text = it.currentActionGroupGross.toString()
        }
        viewModel.uiConsumeTime.observe(this) {
            findViewById<TextView>(R.id.tv_all_time).text = it
        }
        viewModel.lineData.observe(this) {
            LogUtils.i("lineData${it.yValue.size}")
            if (it.yValue != null && it.yValue.size > 0) {
                var that = it
                HANDLER.post {
                    LogUtils.i("lineData start")
                    sportEngine?.addKCal(it.cal)
                    findViewById<TextView>(R.id.tv_cal).text = sportEngine?.kcal
                    var char = findViewById<LineChart>(R.id.id_add_char)
                    var lineData = char.lineData
                    lineData?.let {
                        that.yValue.forEach {
                            lineData.addEntry(Entry(lineData.entryCount.toFloat(), it.toFloat()), 0)
                        }
                        var valueFormatter = char.xAxis.valueFormatter as IndexAxisValueFormatter
                        var values = valueFormatter.getValues().toMutableList()
                        values.addAll(that.xLabel)
                        valueFormatter.values = values.toTypedArray()
                        char.xAxis.valueFormatter = valueFormatter
                        char.scaleX_OBJ((it.entryCount + 1) / 3)
                        char.notifyDataSetChanged()
                        char.moveViewTo(
                            it.entryCount.toFloat(),
                            that.yValue.get(that.yValue.size - 1).toFloat(),
                            YAxis.AxisDependency.LEFT
                        )
                    }
                }
            }

        }

    }

    override fun upDataCount(count: Int?) {
        if (sportEngine != null) {
            viewModel?.pauseSport.let {
                if (!it) {
                    sportEngine?.addCount()
                }
            }

        }
    }

    /**转速,力矩,功率*/
    override fun onDataReceived(speed: Int, moment: Int, power: Int) {
        if (sportEngine != null) {
            viewModel.onNext(SportReceive(speed, moment, power, sportEngine!!.currentCount))
        }

    }

    var dialogList = HashMap<Int, DialogError.Builder>()

    override fun errorList(cmdExceptions: MutableList<CmdException>) {
        HANDLER.post {
            for (cmdException in cmdExceptions) {
                if (cmdException.error) {
                    if (dialogList.containsKey(cmdException.id)) {
                        dialogList[cmdException.id]?.show()
                    } else {
                        DialogError.Builder(context).also {
                            it.setError(cmdException.name)
                        }.show()
                    }
                }

            }
        }

    }


    override fun onClick(v: View) {
        super.onClick(v)
        when (v.id) {
            R.id.add -> {
                sportEngine?.addCount()
                for (i in 0..10) {
                    onDataReceived(
                        Random().nextInt(9999),
                        Random().nextInt(9999),
                        Random().nextInt(9999)
                    )
                }
//                var arr = mutableListOf<CmdException>()
//                arr.add(CmdException().also {
//                    it.error = true
//                    it.id = Random().nextInt(5)
//                    it.name = "报错"
//                })
//                errorList(arr)
            }
            R.id.id_add_m -> {
                v.isSelected = !v.isSelected
                if (v.isSelected) {
                    player.pausePlay()
                    viewModel.stopSport()
                } else {
                    player.startPlay()
                    viewModel.resumeSport()
                }
            }
            R.id.id_add_music -> {
                v.isSelected = !v.isSelected
                if (v.isSelected) {
                    player.onVolumeControllerChangeListener.onProgressChanged(null, 0, false)
                } else {
                    player.onVolumeControllerChangeListener.onProgressChanged(null, 100, false)
                }

            }
            R.id.id_add_m1 -> {
                sportEngine?.cutAction(false)
            }
            R.id.id_add_m2 -> {
                sportEngine?.cutAction(true)
            }
        }
    }

    override fun onRightClick(v: View?) {
        super.onRightClick(v)
        if (!powerDialog.isShowing) {
            powerDialog.show()
        }
    }

    override fun onDestroy() {
        super.onDestroy()
        player?.let {
            player.stopPlay()
            player.onDestroy()
        }
    }


}